<?php


namespace PKApp\Content\Classes;


use PKApp\Content\Model\CategoryModel;
use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\Auth;
use PKFrame\DataHandler\Numbers;

trait TraitContent
{
    // 是否发布静态的列表页
    // 用于区分实体栏目信息的模板赋值
    protected $is_makeHtml_category;
    protected $listCatId_noMakeHtml = [], $list_url = [];

    protected function serviceOfCategory(int $id_site): CategoryService
    {
        static $cls;
        !is_array($cls) ?: $cls = [];
        if (!array_key_exists($id_site, $cls)) {
            $cls[$id_site] = new CategoryService($id_site);
        }
        return $cls[$id_site];
    }

    protected function serviceOfContent(int $id_model): ContentService
    {
        static $cls;
        if (!is_array($cls) || !array_key_exists($id_model, $cls)) {
            $cls[$id_model] = new ContentService($id_model);
        }
        return $cls[$id_model];
    }

    protected function serviceOfLogPushBaiDu(): LogPushBaiDuService
    {
        static $cls;
        !empty($cls) ?: $cls = new LogPushBaiDuService();
        return $cls;
    }

    protected function serviceOfPage(): PageService
    {
        static $cls;
        !empty($cls) ?: $cls = new PageService();
        return $cls;
    }

    final protected function getCategoryEntityByNow($is_reaStart = false): CategoryModel
    {
        static $m;
        if (empty($m) || $is_reaStart) {
            $entity = $this->serviceOfCategory(
                $this->getSiteEntity()->Id
            )->interface_getEntityById(
                $this->getIdOfCategory()
            );
            if ($entity['categoryType'] != 'link') {
                $entity['url'] = self::UrlPathOfCategory($entity, $entity['template'], $this->getSitePath());
            }
            $m = new CategoryModel($entity);
            if (array_key_exists('info', $entity)) {
                $entity['info'] = Auth::HtmlspecialcharsDeCode($entity['info']);
            }
            if (array_key_exists('template', $entity)) {
                unset($entity['template']);
            }
            if (array_key_exists('setting', $entity)) {
                unset($entity['setting']);
            }
            if (array_key_exists('parentIdList', $entity) && !empty($entity['parentIdList'])) {
                $this->assign('categoryParentIdList', explode(',', $entity['parentIdList']));
            }
            $is_preView = (request()->controller() == 'Category');
            if (($is_preView || $this->is_makeHtml_category) && ($entity['categoryType'] == 'list')) {
                $this->assign($entity);
            } else {
                $this->assign('category', $entity);
            }
        }
        return $m;
    }

    protected function getIdOfCategory(): int
    {
        return $this->getId('catId', 'Category_idEmpty', 'content');
    }

    protected function getIdOfModel(): int
    {
        static $id_model;
        if (!Numbers::IsId($id_model)) {
            $id_model = $this->getId('modelId');
            if (!Numbers::IsId($id_model)) {
                $id_model = $this->postId('modelId');
            }
            Numbers::IsId($id_model) ?: out()->noticeByLJson('Model_IdEmpty', 'model');
        }
        return $id_model;
    }

    /**
     * 栏目的URL转换
     * @param $category
     * @param $templateConfig
     * @param null $sitePath
     * @param bool $isPageNav
     * @return mixed|string
     */
    protected static function UrlPathOfCategory($category, $templateConfig, $sitePath = NULL, $isPageNav = false): string
    {
        $isRewrite = in_array($category['categoryType'], array('page', 'list')) &&
            (((array_key_exists('categoryHtml', $templateConfig) && $templateConfig['categoryHtml']) ||
                    (array_key_exists('pageHtml', $templateConfig) && $templateConfig['pageHtml'])) ||
                $templateConfig['isRewrite']);
        switch ($category['categoryType']) {
            case 'page':
                if ($isRewrite) {
                    $url = str_replace('[id]', $category['id'], $templateConfig['pageUrl']);
                    return '/' . (empty($sitePath) ? $url : $sitePath . '/' . $url);
                } else {
                    return '/index.php/content/category?siteId=' . $category['siteId'] . '&catId=' . $category['id'];
                }
            case 'list':
                if ($isRewrite) {
                    $url = preg_replace('(\[id\]|\[catId\])', $category['id'], $templateConfig['categoryUrl']);
                    $isPageNav ?: $url = preg_replace('(-\[page\]|_\[page\]|/\[page\]|\[page\])', '', $url);
                    return '/' . (empty($sitePath) ? $url : $sitePath . '/' . $url);
                } else {
                    return '/index.php/content/category?siteId=' . $category['siteId'] . '&catId=' . $category['id']
                        . ($isPageNav ? '&pageIndex=[page]' : '');
                }
            case 'link':
                return $category['url'];
        }
        return '';
    }

    /**
     * 内容页URL规则
     * @param array $category
     * @param array $templateConfig
     * @param array $content
     * @param string|NULL $sitePath
     * @param int|null $pageCode
     * @return string
     */
    protected static function UrlPathOfContent(array $category, array $templateConfig, array $content, string $sitePath = NULL, int $pageCode = null): string
    {
        $isPage = !is_null($pageCode) && Numbers::IsId($pageCode);
        $isRewrite = $templateConfig['contentHtml'] || $templateConfig['isRewrite'];
        if ($isRewrite && !empty($content['url'])) {
            $url = ltrim($content['url'], '/');
        } elseif ($isRewrite && array_key_exists('contentHtml', $templateConfig)
            && boolval($templateConfig['contentHtml'])) {
            $url = str_replace('[id]', $content['id'], $templateConfig['contentUrl']);
            $url = str_replace(['[modelId]', '[modelid]'], $category['modelId'], $url);
            $url = str_replace(['[catId]', '[catid]'], $category['id'], $url);
            if ($isPage && $pageCode > 1) {
                $url_arr = explode('.', $url);
                $url = $url_arr[0] . '-' . $pageCode . '.' . $url_arr[1];
            }
        } else {
            $url = '/index.php/content/content?catId=' . $category['id'] . '&contentId=' . $content['id'];
            return $url . ($isPage ? '&page=' . $pageCode : null);
        }
        return '/' . (empty($sitePath) ? $url : $sitePath . '/' . $url);
    }

    protected function getContentUrl(array $list_cat, array $content_entity, array $siteEntity): string
    {
        $tmp_cat = array_filter($list_cat, function ($item_cat) use ($content_entity) {
            return $content_entity['catId'] == $item_cat['id'] ? $item_cat : [];
        });
        if (Arrays::Is($tmp_cat) == 1 && $tmp_cat = array_shift($tmp_cat)) {
            return self::UrlPathOfContent(
                $tmp_cat, $tmp_cat['template'], $content_entity, $siteEntity['Site_Path']);
        }
        return '';
    }

    protected static function UrlPathOfSearch(): string
    {
        $params = request()->get();
        if (array_key_exists('page', $params)) {
            unset($params['page']);
        }
        return '/index.php/content/Search' . '?' . Arrays::ToQuery($params) . '&page=[page]';
    }

    /**
     * 用于发布的栏目递归
     * @param $list_category
     * @param int $id_parent
     * @param string $path_site
     * @return array
     */
    protected function treeOfCategory($list_category, $id_parent = 0, $path_site = ''): array
    {
        $result = [];
        $nowChild = array_filter($list_category, function ($entity) use ($id_parent) {
            return $entity['parentId'] == $id_parent ? $entity : array();
        });
        if (Arrays::Is($nowChild)) {
            foreach ($nowChild as $item) {
                $item_tpl = $item['template'];
                if ($item['categoryType'] == 'list' && !toBool('contentHtml', $item_tpl)) {
                    $this->listCatId_noMakeHtml[] = $item['id'];
                }
                $url = self::UrlPathOfCategory($item, $item_tpl, $path_site);
                $this->list_url[] = ['md5' => md5($url), 'url' => $url];
                $item['url'] = $url;
                $item['child'] = $this->treeOfCategory($list_category, $item['id'], $path_site);
                $result[] = $item;
            }
        }
        return $result;
    }

    /**
     * @return array
     */
    protected function getListCatIdNoMakeHtml(): array
    {
        return $this->listCatId_noMakeHtml;
    }

    /**
     * @return array
     */
    protected function getListUrl(): array
    {
        return $this->list_url;
    }

}